﻿// 数组去重
Array.prototype.unique = function () {
    var n = {}, r = [];
    for (var i = 0; i < this.length; i++) {
        if (!n[this[i]]) {
            n[this[i]] = true;
            r.push(this[i]);
        }
    }
    return r;
}
//交集
//交集元素由既属于集合A又属于集合B的元素组成
// 使用方式
//Array.intersect([1, 2, 3, 4], [3, 4, 5, 6]); // [3,4]

Array.intersect = function (arr1, arr2) {
    if (Object.prototype.toString.call(arr1) === "[object Array]" && Object.prototype.toString.call(arr2) === "[object Array]") {
        return arr1.filter(function (v) {
            return arr2.indexOf(v) !== -1
        })
    }
}

//并集
//并集元素由集合A和集合B中所有元素去重组成
//// 使用方式
//Array.union([1, 2, 3, 4], [1, 3, 4, 5, 6]); // [1,2,3,4,5,6]
Array.prototype.union = function (arr) {
    if (Object.prototype.toString.call(arr) === "[object Array]") {
        return this.concat(arr).unique()
    }
}
//差集
//A的差集：属于A集合不属于B集合的元素
//B的差集：属于B集合不属于A集合的元素
//// 使用方式
//var arr = [1, 2, 3, 4];
//arr.minus([2, 4]); // [1,3]
Array.prototype.minus = function (arr) {
    if (Object.prototype.toString.call(arr) === "[object Array]") {
        var interArr = Array.intersect(this, arr);// 交集数组
        return this.filter(function (v) {
            return interArr.indexOf(v) === -1
        })
    }
}
//数组差
Array.prototype.diff = function (a) {
    return this.filter(function (i) { return a.indexOf(i) < 0; });

};
// ES6 的 Set 来处理，这是真正按照数学上的集合来进行的，不会有重复元素
var subSet = function subSet(arr1, arr2) {
    var set1 = new Set(arr1);
    var set2 = new Set(arr2);

    var subset = [];

    for (let item of set1) {
        if (!set2.has(item)) {
            subset.push(item);
        }

    }
    return subset;
};
//判断对象是否相等
function isObjectValueEqual(a, b) {
    // Of course, we can do it use for in 
    // Create arrays of property names
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // If number of properties is different,
    // objects are not equivalent
    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        // If values of same property are not equal,
        // objects are not equivalent
        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    // If we made it this far, objects
    // are considered equivalent
    return true;
}

Date.prototype.toLocaleString = function () {
    function addZero(num) {
        if (num < 10)
            return "0" + num;
        return num;
    }
    return this.getFullYear() + "-" + addZero(this.getMonth() + 1) + "-" + addZero(this.getDate()) + " " + addZero(this.getHours()) + ":" + addZero(this.getMinutes()) + ":" + addZero(this.getSeconds());
};
function changeDateFormat(cellval) {
    var tempdate = new Date(cellval);
    return tempdate.toLocaleString();
};
function splitData(rawData) {
    var categoryData = [];
    var values = []
    $.each(rawData, function (index, item) {
        categoryData.push(item.splice(0, 1)[0]);
        values.push(item)
    })
    return {
        categoryData: categoryData,
        values: values
    };
}

function calculateMA(dayCount, dataObj) {
    var result = [];
    //var data0 = splitData(arry);
    for (var i = 0, len = dataObj.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += dataObj.values[i - j][1];
        }
        result.push(sum / dayCount);
    }
    return result;
}
//获取合约数据
function gethyhq(code) {
    $.getJSON('http://122.14.208.164:19000/index?m=test&a=get_real', { symbol: code },
        function (data) {
            var data2 = data.data
                .replace(/'/g, '"')
                .replace(/nan/g, '"nan"')
                .replace(/False/g, 'false')
                .replace(/True/g, 'true');
            var json = eval('(' + data2 + ')');
            //console.log('gethyhq json', json)
            $(".sell_price").html(json.ask_price1);
            $(".sell_num").html(json.ask_volume1);
            $(".buy_price").html(json.bid_price1);
            $(".buy_num").html(json.bid_volume1);
            $(".hold").html(json.open_interest);
        });

}

//从天勤获取K线数据 
function GetKlineData(code) {
    var p = new Promise(function (resolve, reject) {
        var arr = [];
        $.getJSON('http://122.14.208.164:19000/index?m=test&a=get_kline&duration_seconds=60', { symbol: code }, function (data) {
            var TQData = eval('(' + data.data + ')');
            var datetime = TQData.datetime;
            var open = TQData.open;
            var close = TQData.close;
            var high = TQData.high;
            var low = TQData.low;
            var arry1 = [];
            $.each(datetime, function (index, item) {
                var stamptime = datetime[index]
                var datestr = changeDateFormat(Math.round(stamptime / 1000000) + index * 0);
                arry1.push(datestr);
                arry1.push(open[index]);
                arry1.push(close[index]);
                arry1.push(low[index]);
                arry1.push(high[index]);
                arr.push(arry1)
                arry1 = [];
            });
            resolve(arr);
        });
    });
    return p;

}

function MakeKLine2(code) {
    var dom = document.getElementById("container");
    var myChart = echarts.init(dom);
    GetKlineData(code).then(function (data) {
        SetKline2(myChart, data, code) 
    }); 
    setInterval(function () {
        GetKlineData(code).then(function (data) { 
            let dataObj = splitData(data);
            $.post('/Mobile/MIndex/GetMyHyByCode', { code: code }, function (data) {

                var pointjson = eval('(' + data + ')');
                var pointdata = [
                    {
                        name: 'highest value',
                        type: 'max',
                        valueDim: 'highest'
                    },
                    {
                        name: 'lowest value',
                        type: 'min',
                        valueDim: 'lowest'
                    },
                    {
                        name: 'average value on close',
                        type: 'average',
                        valueDim: 'close'
                    }
                ];
                $.each(pointjson, function (index, item) {

                    var point =
                    {
                        name: item.F_Id,
                        coord: [item.tradingday, item.currentprice],
                        value: '',
                        itemStyle: {
                            color: setColor(item.direction, item.openclose)
                        },
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: item.openclose + item.direction, 
                        }
                    };
                    pointdata.push(point);
                });
        ////////////////////////////////////////////////////////



                myChart.setOption({
                    series: [{
                        data: dataObj.values,
                        markPoint: {
                            data: pointdata
                        }
                    }]
                });
                console.log('设置数据')
            })
          
        });
    }, 3000); 

}
function updateKline(myChart, code) {
    GetKlineData(code).then(function (arry) { 
        let dataObj = splitData(arry);
        myChart.setOption({
            series: [{
                type: 'candlestick',
                data: dataObj.values
            }]
        });
        setTimeout(function () { updateKline(myChart, code) }, 3000);
    });
}

function SetKline2(myChart, arry, code) {
    var upColor = '#ec0000';
    var upBorderColor = '#8A0000';
    var downColor = '#00da3c';
    var downBorderColor = '#008F28';
    var dataObj = splitData(arry);
    var option;

    $.post('/Mobile/MIndex/GetMyHyByCode', { code: code }, function (data) {
        var pointjson = eval('(' + data + ')');
        var pointdata = [
            {
                name: 'highest value',
                type: 'max',
                valueDim: 'highest'
            },
            {
                name: 'lowest value',
                type: 'min',
                valueDim: 'lowest'
            },
            {
                name: 'average value on close',
                type: 'average',
                valueDim: 'close'
            }
        ];
        $.each(pointjson, function (index, item) {

            var point =
            {
                name: item.F_Id,
                coord: [item.tradingday, item.currentprice],
                value: '',
                itemStyle: {
                    color: setColor(item.direction, item.openclose)
                },
                label: {
                    show: true,
                    position: 'inside',
                    formatter: item.openclose + item.direction,
                    //color:'#000'
                }
            };
            pointdata.push(point);
        });
        ////////////////////////////////////////////////////////



        option = {
            title: {
                text: '',
                left: 0
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            legend: {
                data: ['实时', '5分钟', '10分钟', '20分钟', '30分钟']
            },
            grid: {
                left: '10%',
                right: '10%',
                bottom: '1%'
            },
            xAxis: {
                type: 'category',
                data: dataObj.categoryData,
                scale: true,
                boundaryGap: false,
                axisLine: { onZero: false },
                splitLine: { show: false },
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            },
            yAxis: {
                scale: true,
                splitArea: {
                    show: true
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    top: '90%',
                    start: 0,
                    end: 100
                }
            ],
            series: [
                {
                    name: '实时',
                    type: 'candlestick',
                    data: dataObj.values,
                    itemStyle: {
                        color: upColor,
                        color0: downColor,
                        borderColor: upBorderColor,
                        borderColor0: downBorderColor
                    },
                    markPoint: {
                        label: {
                            normal: {
                                formatter: function (param) {
                                    //console.log('markpoint normal param', param);
                                    return param != null ? Math.round(param.value) : '';
                                }
                            }
                        },
                        data: pointdata,
                        tooltip: {
                            formatter: function (param) {
                                //console.log('markpoint tooltip param', param);
                                return param.name + '<br>' + (param.data.coord || '');
                            }
                        }
                    },
                    markLine: {
                        symbol: ['none', 'none'],
                        data: [
                            [
                                {
                                    name: 'from lowest to highest',
                                    type: 'min',
                                    valueDim: 'lowest',
                                    symbol: 'circle',
                                    symbolSize: 10,
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        label: {
                                            show: false
                                        }
                                    }
                                },
                                {
                                    type: 'max',
                                    valueDim: 'highest',
                                    symbol: 'circle',
                                    symbolSize: 10,
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        label: {
                                            show: false
                                        }
                                    }
                                }
                            ],
                            {
                                name: 'min line on close',
                                type: 'min',
                                valueDim: 'close'
                            },
                            {
                                name: 'max line on close',
                                type: 'max',
                                valueDim: 'close'
                            }
                        ]
                    }
                },
                {
                    name: '5分钟',
                    type: 'line',
                    data: calculateMA(5, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '10分钟',
                    type: 'line',
                    data: calculateMA(10, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '20分钟',
                    type: 'line',
                    data: calculateMA(20, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '30分钟',
                    type: 'line',
                    data: calculateMA(30, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },

            ]
        };


        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }

        //setTimeout(SetKline2(myChart, arry, code),3000)


    });

}


//获取K线数据
function MakeKLine(code) {
    var arry2 = [];
    $.post('/Mobile/MIndex/get_kline', { code: code }, function (data) {
        var KLineData = eval('(' + data + ')');
        //console.log('KLineData', KLineData)
        var datetime = KLineData.data.datetime;
        var open = KLineData.data.open;
        var close = KLineData.data.close;
        var high = KLineData.data.high;
        var low = KLineData.data.low;
        var arry1 = [];
        $.each(datetime, function (index, item) {
            var stamptime = datetime[index]
            //debugger;
            var datestr = changeDateFormat(Math.round(stamptime / 1000000) + index * 0);
            //console.log('datastr', datestr)
            //console.log('datetime', datestr)
            arry1.push(datestr);
            arry1.push(open[index]);
            arry1.push(close[index]);
            arry1.push(low[index]);
            arry1.push(high[index]);

            arry2.push(arry1)
            arry1 = [];
        });
        SetKline(code, arry2);


    })

    setTimeout(function () { MakeKLine(code) }, 5000)
    return arry2;
}

function SetKline(code, arry) {
    var upColor = '#ec0000';
    var upBorderColor = '#8A0000';
    var downColor = '#00da3c';
    var downBorderColor = '#008F28';
    var dom = document.getElementById("container");
    var myChart = echarts.init(dom);
    var dataObj = splitData(arry);
    var option;

    $.post('/Mobile/MIndex/GetMyHyByCode', { code: code }, function (data) {
        var pointjson = eval('(' + data + ')');
        //console.log('GetMyHyByCode', pointjson);
        var pointdata = [
            //{
            //    name: 'XX标点',
            //    coord: ['2021-02-19 21:44:00', 9188],
            //    value: 9188,
            //    itemStyle: {
            //        color: '#000099'
            //    }
            //},
            {
                name: 'highest value',
                type: 'max',
                valueDim: 'highest',
                //itemStyle: {
                //    color: '#008F28'
                //}
            },
            {
                name: 'lowest value',
                type: 'min',
                valueDim: 'lowest'
            },
            {
                name: 'average value on close',
                type: 'average',
                valueDim: 'close'
            }
        ];
        $.each(pointjson, function (index, item) {

            var point =
            {
                name: item.F_Id,
                coord: [item.tradingday, item.currentprice],
                value: '',
                itemStyle: {
                    color: setColor(item.direction, item.openclose)
                },
                label: {
                    show: true,
                    position: 'inside',
                    formatter: item.openclose + item.direction,
                    //color:'#000'
                }
            };
            pointdata.push(point);

            //pointdata.push({
            //    name: item.F_Id,
            //    coord: [item.tradingday, item.currentprice],
            //    value: item.currentprice,
            //    itemStyle: {
            //        color: setColor(item.direction, item.openclose)
            //    }
            //});
        });
        /////////////////////////////////////////////////////////////////

        option = {
            title: {
                text: '',
                left: 0
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            legend: {
                data: ['实时', '5分钟', '10分钟', '20分钟', '30分钟']
            },
            grid: {
                left: '10%',
                right: '10%',
                bottom: '1%'
            },
            xAxis: {
                type: 'category',
                data: dataObj.categoryData,
                scale: true,
                boundaryGap: false,
                axisLine: { onZero: false },
                splitLine: { show: false },
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            },
            yAxis: {
                scale: true,
                splitArea: {
                    show: true
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    top: '90%',
                    start: 0,
                    end: 100
                }
            ],
            series: [
                {
                    name: '实时',
                    type: 'candlestick',
                    data: dataObj.values,
                    itemStyle: {
                        color: upColor,
                        color0: downColor,
                        borderColor: upBorderColor,
                        borderColor0: downBorderColor
                    },
                    markPoint: {
                        label: {
                            normal: {
                                formatter: function (param) {
                                    //console.log('markpoint normal param', param);
                                    return param != null ? Math.round(param.value) : '';
                                }
                            }
                        },
                        data: pointdata,
                        tooltip: {
                            formatter: function (param) {
                                //console.log('markpoint tooltip param', param);
                                return param.name + '<br>' + (param.data.coord || '');
                            }
                        }
                    },
                    markLine: {
                        symbol: ['none', 'none'],
                        data: [
                            [
                                {
                                    name: 'from lowest to highest',
                                    type: 'min',
                                    valueDim: 'lowest',
                                    symbol: 'circle',
                                    symbolSize: 10,
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        label: {
                                            show: false
                                        }
                                    }
                                },
                                {
                                    type: 'max',
                                    valueDim: 'highest',
                                    symbol: 'circle',
                                    symbolSize: 10,
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        label: {
                                            show: false
                                        }
                                    }
                                }
                            ],
                            {
                                name: 'min line on close',
                                type: 'min',
                                valueDim: 'close'
                            },
                            {
                                name: 'max line on close',
                                type: 'max',
                                valueDim: 'close'
                            }
                        ]
                    }
                },
                {
                    name: '5分钟',
                    type: 'line',
                    data: calculateMA(5, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '10分钟',
                    type: 'line',
                    data: calculateMA(10, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '20分钟',
                    type: 'line',
                    data: calculateMA(20, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '30分钟',
                    type: 'line',
                    data: calculateMA(30, dataObj),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },

            ]
        };


        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }





    });



}

function setColor(direction, openclose) {
    if (direction == '买' && openclose == '开仓')
        return '#FF0000';//红
    else
        if (direction == '买' && openclose == '平仓')
            return '#6600FF';//紫
        else
            if (direction == '卖' && openclose == '开仓')
                return '#FF7F24';//橙
            else
                if (direction == '卖' && openclose == '平仓')
                    return '#9AFF9A';//浅绿
                else
                    return '#FF0000';


}


